//
//  ViewController.swift
//  useCamera
//
//  Created by liy on 2025/1/18.
//

import PhotosUI
import UIKit

import PhotosUI

class ViewController: UIViewController, PHPickerViewControllerDelegate {
  @IBOutlet var imageView: UIImageView!

  var imgs: [UIImage] = []
  @IBAction func openCamera(_ sender: Any) {
    showPicker()
  }

  func showPicker() {
    var configuration = PHPickerConfiguration()
    configuration.filter = .images
    configuration.selectionLimit = 5
    let picker = PHPickerViewController(configuration: configuration)
    picker.delegate = self
    picker.modalPresentationStyle = .overFullScreen
    present(picker, animated: true, completion: nil)
  }

	func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
		let dispatchGroup = DispatchGroup()
			// 处理用户选择的结果
		for result in results {
			dispatchGroup.enter()
			result.itemProvider.loadObject(ofClass: UIImage.self) { (image, error) in
				if let image = image as? UIImage {
						// 在UI上显示选择的图片等操作
					self.imgs.append(image)
				}
				dispatchGroup.leave()
			}
		}
		dispatchGroup.notify(queue: DispatchQueue.main) {
			if let lastImage = self.imgs.last {
				self.imageView.image = lastImage
			}
		}
		picker.dismiss(animated: true, completion: nil)
	}
}
